<?
########################### DRIVER ####################################
//---------------------------------------------------->
function lancia_procedura($procedura,$parametri){
	global $conn;
	$sql = " call ".$procedura." ( ".$parametri." ) ";
	//$stmt = $conn->Prepare($sql);
	$result = $conn->Execute($sql);
	$result && $result->RecordCount() > 0 ?
	$result->MoveFirst():
	$result = null;
	if(is_null($result)) echo "".$conn->ErrorMsg()."";
	return $result;
}

//---------------------------------------------------->
function lancia_funzione($funzione,$parametri){
	global $conn;
	$sql = " select ".$funzione." ( ".$parametri." ) as ris";
	//$stmt = $db_core->Prepare($sql);
	$rs = $conn->Execute($sql);
	if ($rs) {
		$rs->MoveFirst();
		$result = $rs->fields['ris'];
	} else {
		$result = 0;
	}
	return $result;
}
######################## FUNZIONI #################################################
function Get_json($nodo,$rs,$colonne,$conteggio=true) {
		//error_reporting(E_ALL);
		if(!$rs) return total_count_to_json($rs);
		$elenco = Array();
		$record = Array();
		$conta = 0;
		$esegui_conta = true;
		while(!$rs->EOF)  {
			if ($esegui_conta && $rs->Fields('conteggio_record')) {
				$conta = $rs->Fields('conteggio_record'); // controllo se esiste una colonna di conteggio dei record
			}
			$esegui_conta = false;
			foreach($colonne as $k) {
				for($i=0;$i<$rs->FieldCount();$i++){
					$fld = $rs->FetchField($i);
					if($fld->name == $k) break;
				}
				$type = $rs->MetaType($fld->type);
				//echo $type;
				if(is_null($rs->Fields($k))){
					$record[$k] = NULL;
				}elseif ( $type == "C" || $type == "X"){
					if($rs->Fields($k)){
						//$record[$k] = htmlentities(stripslashes($rs->Fields($k)));
						//$record[$k] = utf8_encode($rs->Fields($k));
						$record[$k] = iconv("ISO-8859-15","UTF-8//TRANSLIT",$rs->Fields($k));
						//$record[$k] = mb_convert_encoding($rs->Fields($k),"UTF-8",Array("ISO-8859-15","ISO-8859-1"));
					}else{
						$record[$k] = '';
					}
				}elseif ($type == "T" || $type == "D"){
					if($rs->Fields($k)){
						$record[$k] = date( 'c', strtotime($rs->Fields($k)));
					}else{
						$record[$k] = '';
					}
				}elseif ($type == "L"){
					if($rs->Fields($k)){
						$record[$k] = true;
					}else{
						$record[$k] = false;
					}
				}elseif ($type == "I" || $type == "R"){
					if($rs->Fields($k)){
						$record[$k] = intval($rs->Fields($k));
					}else{
						$record[$k] = 0;
					}
				}elseif ( $type == "N"){
					if($rs->Fields($k)){
						$record[$k] = floatval($rs->Fields($k));
					}else{
						$record[$k] = 0;
					}
				}
			}
			array_push($elenco,$record);
			$rs->MoveNext();
		}
		$result = ($conteggio ? total_count_to_json($rs,$conta).',' : '').'"'.$nodo.'":'.json_encode($elenco);
		return $result;
}

function total_count_to_json($rs,$conta) {
		if($rs){
			if ($conta) {
				$va_rit = '"totalCount":'.$conta;
			} else {
				$va_rit = '"totalCount":'.$rs->RecordCount();
			}
			if (method_exists($rs,'NextRecordSet')) $rs->NextRecordSet();
			$rs->Close();
			return $va_rit;
		} else { 
			return '"totalCount":0';
		}
}

function login($username,$password) {
	$rs = lancia_procedura("login", "'$username','$password'");
	$error = "";
	if($rs->RecordCount()>0) {
		if($rs->Fields("msg")=="") {
			# LOGIN OK #
			$_SESSION['idutente'] = $rs->Fields("idutente");
			$_SESSION['nome'] = $rs->Fields("nome");
			$_SESSION['livello'] = $rs->Fields("livello");
		} else
			$error = $rs->Fields("msg");
		$rs->Close();
	}
	return $error;
}

function login_cliente($username,$password) {
	$rs = lancia_procedura("login_cliente", "'$username','$password'");
	$error = "";
	if($rs->RecordCount()>0) {
		if($rs->Fields("msg")=="") {
			# LOGIN OK #
			$_SESSION['idcliente'] = $rs->Fields("idutente");
		$_SESSION['nome'] = $rs->Fields("nome");
		} else
		$error = $rs->Fields("msg");
		$rs->Close();
	}
	return $error;
}

function rinnovaSessione($json=false) {
	session_start();
	if (isset($_SESSION['HTTP_USER_AGENT']))
	{
	    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
	    {
	        logout();
	        header("Location: index.php");
	        die();
	    }
	    if($_SESSION['idutente']=="") {
	    	if($json) {
	    		die('{"session":1}');
	    	} else {
	    		header("Location: index.php");
	    		die();
	    	}
	    }
	}
	else
	{
	    $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
	}
}

function rinnovaSessioneCliente($json=false) {
	session_start();
	if (isset($_SESSION['HTTP_USER_AGENT']))
	{
		if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
		{
			logout();
	        header("Location: login.php");
	        die();
		}
		if($_SESSION['idcliente']=="") {
			if($json) {
				die('{"session":1}');
			} else {
				header("Location: login.php");
				die();
			}
		}
	}
	else
	{
		$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
	}
}

function logout() {
	$_SESSION = Array();
	session_write_close();
}

function encodeUtf8Array($post) {
	foreach ($post as $key=>$value) {
		$post[$key] = utf8_encode($value);
	}
	return $post;
}

function decodeUtf8Array($post) {
	foreach ($post as $key=>$value) {
		$post[$key] = utf8_decode($value);
	}
	return $post;
}

function formattaData($data) {
	# da d/m/Y a Y-d-m
	list($d,$m,$y) = explode("/",$data);
	return "$y-$m-$d";
}

function pulisciCartella($str) {
 $pl = strtolower(htmlEnc($str)); 
 $pl = preg_replace("#&([aeiouny])(acute|circ|grave|ring|tilde|uml);#", '$1', $pl);
 $pl = str_replace('&ccedil;','c',$pl);
 $pl = str_replace('&amp;','e',$pl);
 $pl = str_replace('&euro;','e',$pl);
 $pl = preg_replace("#&([ao])elig;#", '$1e', $pl);
 $pl = str_replace('&iexcl;','i',$pl);
 $pl = str_replace('&scaron;','s',$pl);
 $pl = preg_replace("#&sup([1-3]);#", '$1', $pl);
 $pl = preg_replace("#&([^;]+);#", '', $pl);
 $pl = str_replace(' ','-',$pl);
 $pl = preg_replace("#[^a-zA-Z0-9\-_]#", '', $pl);
 while(strstr($pl,'--'))
  $pl = str_replace('--', '-', $pl);
 return $pl;
}

function htmlEnc($str, $nl2br = false) {
 $str = htmlentities($str,ENT_QUOTES, 'UTF-8');
 if ($nl2br)
  return str_replace("\n","<br />",$str);
 else
  return $str;
}

/**
 * Copy a file, or recursively copy a folder and its contents
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.0.1
 * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
 * @param       string   $source    Source path
 * @param       string   $dest      Destination path
 * @return      bool     Returns TRUE on success, FALSE on failure
 */
function copyr($source, $dest, $connect, $cartella)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }
 
    // Simple copy for a file
    if (is_file($source)) {
    	list($rad,$path) = explode("demo",$source);
    	//echo ("httpdocs/".$path);
        return ftp_put($connect, "httpdocs/$cartella/".$path, $source, FTP_BINARY);
    }
 
    // Make destination directory
    if (!is_dir($dest)) {
    	list($rad,$path) = explode("httpdocs",$dest);
        if(!ftp_mkdir($connect, "httpdocs/".$path))
          return false;
    }
 
    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }
 
        // Deep copy directories
        copyr("$source/$entry", "$dest/$entry", $connect, $cartella);
    }
 
    // Clean up
    $dir->close();
    return true;
}

function generatePassword ($length=8) {
	    $password = "";
	    $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
	    $i = 0; 
	    while ($i < $length) { 
	        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
	            if (!strstr($password, $char)) {
	                $password .= $char;
	                $i++;
	            }
	        }
        return $password;
}
?>